<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use backend\models\User;

/**
 * Login form
 */
class EditPassword extends Model
{
    public $oldpwd;
    public $newpwd;
    public $repwd;
    public $id;

    private $_user;


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['oldpwd', 'newpwd', 'repwd'], 'string', 'max' => 255],
            [['oldpwd', 'newpwd', 'repwd'], 'required'],
        ];
    }
    
    public function changePwd(){
        $user = $this->getUser();
        if (!$user || !$user->validatePassword($this->oldpwd)) {
            return ['result' => false, 'msg' => Yii::t('app', 'Old password is incorrect.')];
        }
        if($this->newpwd != $this->repwd){
            return ['result' => false, 'msg' => Yii::t('app', 'The two passwords are inconsistent.')];
        }
        $user->generateAuthKey();
        $user->setPassword($this->newpwd);
        $result = $user->save();
        if($result){
            return ['result' => true, 'msg' => Yii::t('app', 'Edit Password Success')];
        }
        return ['result' => false, 'msg' => Yii::t('app', 'Failure')];
    }


    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findOne($this->id);
        }

        return $this->_user;
    }
    
    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'oldpwd' => Yii::t('app', 'Old Password'),
            'newpwd' => Yii::t('app', 'New Password'),
            'repwd' => Yii::t('app', 'Re Input Password'),
        ];
    }
}
